package busuanzi.oauth;

import com.google.common.base.Strings;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import org.json.JSONObject;

import static sardine.Sardine.get;
import static sardine.Sardine.halt;

/**
 * Created by bruce on 15/12/7.
 */
public class GitHubs {

    static String client_id = "e15fe0df8a38c4006614";
    static String client_secret = "e81c6f95e8d1e93f9b69bde1b878d29b2e48bc76";

    static String authorize_url = "https://github.com/login/oauth/authorize";
    static String access_token_url = "https://github.com/login/oauth/access_token";
    static String api_user_url = "https://api.github.com/user";

    static String redirect_uri = "http://busuanzi.ibruce.info/oauth/github/authorize_callback";
    //    static String redirect_uri = "http://busuanzi.ibruce.info/admin";
    static String scope = ""; // 空，默认值
    static String state = Long.toHexString(System.nanoTime());

    public static void run() {

        // Redirect users to request GitHub access
        get("/oauth/github/authorize", () -> { // 获取地址
            StringBuilder sb = new StringBuilder();
            sb.append(authorize_url);// GitHub的认证接口
            sb.append("?client_id=").append(client_id);
            sb.append("&redirect_uri=").append(redirect_uri); // 下个方法
            sb.append("&scope=").append(scope);// 暂时留空
            sb.append("&state=").append(state); // 校验码
            return sb.toString();
        });

        // GitHub redirects back to your site
        get("/oauth/github/authorize_callback", (request, response) -> {  // authorize回调

            String code = request.queryParams("code");
            String state = request.queryParams("state");

            if (!GitHubs.state.equals(state)) {
                halt("no body");//TODO
            }

//
//            {"access_token":"e72e16c7e42f292c6912e7710c838347ae178b4a", "scope":"repo,gist", "token_type":"bearer"}

            // query Stirng url &&&
            // field mulitiPart
            HttpResponse<JsonNode> resp = Unirest.post(access_token_url)
                    .header("accept", "application/json")
                    .queryString("client_id", client_id)
                    .queryString("client_secret", client_secret)
                    .queryString("code", code)
                    .queryString("redirect_uri", "/oauth/github/access_token_callback")// 应该不起作用
                    .queryString("state", state)
//                            .field("last", "Polo")
                    .asJson();

            JSONObject body = resp.getBody().getObject();


            String access_token = body.getString("access_token");
            String scope = body.getString("scope");
            String token_type = body.getString("token_type");


            if (Strings.isNullOrEmpty(access_token)) {
                halt("no body");//TODO
            }


            HttpResponse<JsonNode> userInfo = Unirest.get(api_user_url)
                    .header("accept", "application/json")
                    .queryString("access_token", access_token)
                    .asJson();


            response.redirect("");

            return "hello hello hello" + System.currentTimeMillis() + " hello hello hello";
        });

//        get("/oauth/github/access_token_callback", (request, response) -> {
//
//            String access_token = request.queryParams("access_token");
//
////            https://api.github.com/user?access_token=xxx
////            curl -H "Authorization: token OAUTH-TOKEN" https://api.github.com/user
//            HttpResponse<JsonNode> resp =
//                    Unirest.post(api_user_url)
//                            .header("accept", "application/json")
//                            .header("authorization", "access_token")
//                            .queryString("client_id", client_id)
//                            .queryString("client_secret", client_secret)
//                            .queryString("code", code)
//                            .queryString("redirect_uri", redirect_uri)
//                            .queryString("state", state)
////                            .field("last", "Polo")
//                            .asJson();
//
//
//            return null;
//        });
    }


    public void access_token() {
//        POST https://github.com/login/oauth/access_token


    }

    public static void main(String[] args) throws Exception {
//        String dd = "https://github.com/login/oauth/authorize?client_id=36d08d88f52b6edf45e4&" +
//                "redirect_uri=http%3A%2F%2Ftoutiao.io%2Fauth%2Fgithub%2Fcallback&" +
//                "response_type=code&state=304b9a107d019efdcc946144475651a27e150f61c199a389";
//        System.out.println(URLDecoder.decode(dd));

        String auth = "http://busuanzi.ibruce.info/admin?code=b5f2c6ce8a2fdf3f46a7";

        HttpResponse<String> resp =
                Unirest.post("https://github.com/login/oauth/access_token")
                        .header("accept", "application/json")
                        .queryString("client_id", "e15fe0df8a38c4006614")
                        .queryString("client_secret", "e81c6f95e8d1e93f9b69bde1b878d29b2e48bc76")
                        .queryString("code", "b5f2c6ce8a2fdf3f46a7")
                        .queryString("redirect_uri", "http://busuanzi.ibruce.info/admin")
                        .queryString("state", "")
//                            .field("last", "Polo")
                        .asString();
//        {"access_token":"a9787b0c2f787d31a29b8e2f2adaa5432bc1c91e","token_type":"bearer","scope":""}

        System.out.println(resp.getBody());

    }


}
